package com.qipay.security.sign.service;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;

@Component
public class SignService {

    public String getSign(Map<String, Object> map, String key, String signKey) {
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            if (entry.getValue() != null && StringUtils.isNotBlank(entry.getValue().toString())
                    && !StringUtils.equals(entry.getKey(), signKey)) {
                list.add(entry.getKey() + "=" + entry.getValue() + "&");
            }
        }

        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "key=" + key;
        result = DigestUtils.md5Hex(result).toUpperCase();
        return result;
    }

    public String getSign(Map<String, Object> map, String key) {
        return getSign(map, key, null);
    }

    public String getSignFromStringArray(Map<String, String[]> map, String key, String signKey) {
        ArrayList<String> list = new ArrayList<String>();
        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            if (entry.getValue() != null && entry.getValue().length > 0 && !StringUtils.equals(entry.getKey(), signKey)) {
                list.add(entry.getKey() + "=" + String.join(",", entry.getValue()) + "&");
            }
        }

        int size = list.size();
        String[] arrayToSort = list.toArray(new String[size]);
        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(arrayToSort[i]);
        }
        String result = sb.toString();
        result += "secret=" + key;
        result = DigestUtils.md5Hex(result).toUpperCase();
        return result;
    }

    public String getSignFromStringArray(Map<String, String[]> map, String key) {
        return getSignFromStringArray(map, key, null);
    }
}
